import re
from .base import BaseConfig
from lib.conf.config import settings


class Disk(BaseConfig):

    def process(self, command_func, debug):
        if debug:
            with open(settings.BASE_DIR + '/files/disk.out', 'r', encoding='utf-8') as f:
                output = f.read(65535)
        else:
            output = command_func("sudo MegaCli  -PDList -aALL")
        return self.parse(output)

    def parse(self, content):
        """
        解析shell命令返回结果
        :param content: shell 命令结果
        :return:解析后的结果
        """
        response = {}
        result = []
        for row_line in content.split("\n\n\n\n"):
            result.append(row_line)
        for item in result:
            temp_dict = {}
            for row in item.split('\n'):
                if not row.strip():
                    continue
                if len(row.split(':')) != 2:
                    continue
                key, value = row.split(':')
                name = self.mega_patter_match(key)
                if name:
                    if key == 'Raw Size':
                        raw_size = re.search('(\d+\.\d+\s\w\w)', value.strip())
                        if raw_size:
                            temp_dict[name] = raw_size.group()
                        else:
                            raw_size = '0'
                    else:
                        temp_dict[name] = value.strip()
            if temp_dict:
                response[temp_dict['slot']] = temp_dict
        return response

    @staticmethod
    def mega_patter_match(needle):
        grep_pattern = {
            'Slot': 'slot',  # 硬盘槽位
            'Raw Size': 'capacity',  # 硬盘容量
            'Inquiry': 'model',  # 获取磁盘编号
            'PD Type': 'pd_type'  # 获取磁盘类型：SAS
        }
        for key, value in grep_pattern.items():
            if needle.startswith(key):
                return value
        return False